<?php
	/**
	* 管理员 能够添加的接口
	*
	* @author yufu 2013-01-12 11:23:17
	*/
	class api extends core{

		//api 接口表
		private $table_api = 'api';

		//接口 组 表
		private $table_api_cat = 'api_cat';

		//绑定接口组
		private $table_bind_api = 'api_bind';

		//接口关联信息表
		private $table_api_conn = 'api_conn' ;

		//公司信息表
		private $table_company = 'my_community_company';

		//城市表
		private $table_city = 'city';

		//个人用户基础表
		private $table_user='my_user';

		//用户表
		private $table_user_extend = 'my_user_extend';

		//用户基本表
		private $table_user_base = 'my_user_base';

		private $table_community = 'my_community';

		private $table_section = 'my_section';

		private $table_admin_proxy_config = 'my_proxy_config';

        //软件崩溃日志
        private $table_crash_log = 'crash_log' ;
		/**
		* 得到客户端使用的配置参数
		* @author zhufu 2013-06-14
		*
		*/
		public function config(){
			global $_site;
			$result = array(
			'score_to_lottery'=>10,  //获得一次摇奖机会需要的积分数量
			'rock_num' => $_site->site_config['site']['rock_num'],   //每天默认的摇奖次数
			'nologin_rock_num' => $_site->site_config['site']['nologin_rock_num']   //每天默认的摇奖次数
			);
			return $result;
		}

		/**
		* 接口日志写入文件
		* @author zhufu 2013-07-24
		*
		* @param mixed $ctn
		*/
		public function api_logs($ctn){
			if(is_array($ctn)){
				$ctn = var_export($ctn, true);
			}
			if(!$ctn){
				return false;
			}
			$logsfile = $this->_root() . '/data/logs/api.txt';
			$fp = @fopen($logsfile, 'a+');
			$ctn = "=============================\r\n" . $ctn ."\r\n";
			@fwrite($fp, $ctn);
		}


		/**
		* 统计客户端定位的城市信息
		* @author zhufu 2013-04-02
		*
		* @param string $city_name 城市名
		* @param int $state 结果状态
		*/
		public function pos_city_static($city_name, $state){
			if(!$city_name){
				return false;
			}
			//手机类型
			$mobile_type = _mobile_type();
			$mobile_type = $mobile_type == 'wtai://wp/mc;' ? "android/web" : "ios";
			//ip
			$ip = get_remote_ip();
			//时间
			$date = date('m-d H:i:s');
			//客户端类型
			$agent_type = $_SERVER['HTTP_USER_AGENT'];
			if(strpos($agent_type, 'Firefox')){
				$agent_type = 'Firefox';
			}elseif(strpos($agent_type, 'MSIE')){
				$agent_type = 'IE';
			}elseif(strpos($agent_type, 'Chrome')){
				$agent_type = 'Chrome';
			}


			$str = sprintf("%s,%d,%s,%s,%s,%s\r\n", $city_name, $state, $ip, $mobile_type, $date, $agent_type);
			//写入文件
			$filename = $this->_root() . '/data/logs/api_city_pos.txt';
			$f1 = @fopen($filename, 'a');
			if(!$f1){
				return false;
			}
			$result = @fwrite($f1, $str);
			if($result === false){
				return false;
			}
			fclose($f1);
			return true;
		}


		/**
		* 根据城市名称，得到城市列表信息，可以是多条数据
		* @author zhufu 2013-03-04 09:32:08
		*
		* @param string $city   要查询的城市名称
		*/
		public function get_city_by_name($city, $eq=true){
			if(!$city){
				return false;
			}
			$sql = "SELECT id,area,main FROM {$this->table_city} WHERE";
			if($eq){
				$sql .= " city_name='{$city}'";
			}
			else{
				$sql .= " city_name like '%{$city}%'";
			}
			return $this->memcache_find($sql);
		}


		/**
		* 根据ID，得到已经开通的城市
		* @author zhufu 2013-03-23
		*
		* @param int $id 获取的实际城市的ID
		*/
		public function get_opend_city($id){
			if(!is_numeric($id)){
				return false;
			}
			//得到对应的二级ID
			$id2 = substr($id, 0, 4) . str_repeat('0', 2);
			//一级id
			$area = substr($id, 0, 2);

			$sql = "select * from {$this->table_city} where main=1 and id={$id2}";
			$row = $this->memcache_findone($sql);
			if($row){
				return $row;
			}

			//本身是二级，直接获取省份默认城市
			$sql = "select * from {$this->table_city} where main=2 and area={$area}";
			$row = $this->memcache_findone($sql);
			return $row;
		}

		/**
		* 根据城市区域得到省会城市信息
		* @author zhufu 2013-03-04 09:49:16
		*
		* @param int $area  城市的区域值
		*/
		public function get_main_by_area($area){
			if(!is_numeric($area)){
				return false;
			}
			$sql = "SELECT id,city_name FROM {$this->table_city} WHERE area={$area} AND main=1 AND state=0";
			return $this->memcache_findone($sql);
		}

		/**
		* 检查用户是否有接口访问权限
		* @author leiqianyong 2013-01-18
		*
		* @param string $app 接口申请名
		* @param string $key  密钥
		* @param string $action 接口
		* @param string authod 授权认证码
		*
		* @return int 0 接口请求失败
		* @return int 1 //接口应用被禁用或未开启
		* @return int 2 //接口连接被禁用或未开启
		* @return int 3 //接口被禁用
		* @return int 4 授权认证码错误
		* @return int 5 今天不能再使用接口了
		*/
		public function check($app,$key,$action,$authod=''){
			//查询接口数据
            //原来直接查询的方式
            //$sql = "SELECT id,authod,public FROM {$this->table_api} WHERE `action`='{$action}' AND `state`=0";            
            //$row = $this->memcache_findone($sql);
            
            $filename = 'api_list';
            $result = F($filename);
            if(!$result){
                $sql = "SELECT id,action,authod,public FROM {$this->table_api} WHERE `state`=0";
                $list = $this->_mysql(0)->find($sql);
                
                if(!$list){
                    return 0;
                }
                $result = array();
                foreach($list as $v){
                    $tmp = md5($v['action']);
                    $result[$tmp] = array('id'=>$v['id'],'authod'=>$v['authod'],'public'=>$v['public']);
                }
                F($filename, $result);                
            }
            $tmp = md5($action);
            $row = $result[$tmp];

            
            if(!$row){
                return false;
            }
			//接口是公用的，直接返回 true
			if($row['public'] == 1){
				return true;
			}
			$key = md5($key);
			$sql = "SELECT id FROM {$this->table_bind_api} WHERE `appkey`='{$app}' AND `secret`='{$key}' AND `state`=0";
			$bind_row = $this->memcache_findone($sql);
			if(!$bind_row){
				return 1;
			}
			$sql = "SELECT id,authod,use_time,rate,use_count FROM {$this->table_api_conn} WHERE `bid`={$bind_row['id']} AND `gid`={$row['id']} AND `state`=0";
			$conn_row = $this->memcache_findone($sql);
			if(!$conn_row){
				return 2;
			}
			if($row['authod']==1 && $authod=='' && $conn_row['authod'] != $authod){
				return 4;
			}

			$today = strtotime('today') ;
			//判断接口的使用频率，暂时取消
			/*if($conn_row['use_time']==$today && $conn_row['rate']<=$conn_row['use_count']){
			return 5 ;
			} */
			//重新设置访问频率
			if($conn_row['use_time'] < $today){
				$conn_row['use_count'] = 0 ;
			}
			$data['use_time'] = $today ;
			$data['use_count'] = $conn_row['use_count'] + 1 ;
			$where = "id={$conn_row['id']}" ;
			$this->set_db($this->table_api_conn,$data,false,$where);
			//允许访问
			return true;
		}




		/*****************  个人用户操作方法  *********************************/

		/**
		* 根据登录认证码，判断个人用户是否登录，并返回个人用户ID
		* @author zhufu 2013-03-28
		*
		* @param string $loginkey 登录认证码
		*/
		public function user_is_login($loginkey){
			if(!$loginkey){
				return false;
			}
			$login_ary=$this->loginkey_change($loginkey);
			//  $result = $this->cache_api('info', "account={$login_ary[2]}&id={$login_ary[0]}");
			$result=$this->_out_info_base($login_ary[0]);
			if(!$result||$result['account'] != $login_ary[2] || $result['password'] != $login_ary[3]){
				return false;
			}
			$extend_info = $this->user_extend_info($result['id']);
			//账号被禁用，则返回未登录
			if($extend_info['state_user'] == 1){
				return false;
			}
			//每天清空领取的摇奖记录
			$today = strtotime(date('Y-m-d'));

			if($extend_info['rock_num_time'] < $today){
				//有效时间在今天之前，
				$sql = "UPDATE {$this->table_user_extend} SET rock_num_last=0 , rock_num_time={$today} WHERE uid={$result['id']}";
				$this->_mysql(0)->query($sql, true);
			}

			return $result['id'];
		}

		/**
		* 得到用户基本信息
		* @author zhufu 2013-08-06
		*
		* @param string $loginkey 用户认证码
		*/
		public function user_info_base($loginkey){
			if(!$loginkey){
				return false;
			}
			$login_ary=$this->loginkey_change($loginkey);
			// $result = $this->cache_api('info', "account={$login_ary[2]}&id={$login_ary[0]}");
			$result=$this->_out_info_base($login_ary[0]);
			if(!$result||$result['account'] != $login_ary[2] || $result['password'] != $login_ary[3]){
				return false;
			}
			return $result;
		}

		/**
		* 修改用户信息
		* @author zhufu 2013-06-19
		*
		* @param int $uid 用户ID
		* @param array $data 用户信息
		*/
		public function _edit_info_extend($uid, $data){
			if(!is_numeric($uid) || !$data || !is_array($data)){
				return false;
			}

			return $this->set_db($this->table_user_extend, $data, false, "uid={$uid}");
		}


		/**
		* loginkey的转换
		* @author limin 2013-6-5 AM 9:40:00
		*/
		public function loginkey_change($loginkey){
			if(!$loginkey){
				return false;
			}
			$loginkey=base64_decode($loginkey);
			$login_ary=array();
			if($loginkey){
				$login_ary=explode('_',$loginkey);
			}
			return $login_ary;
		}

		/**
		* 得到用户信息
		* @author zhufu 2013-03-28
		*
		* @param mixed $ids 单个或者多个ID
		*/
		public function user_list($ids){
			$list = $this->user_api('user', 'list', "ids={$ids}");
			return $list;
		}

		/**
		* 得到用户信息
		* @author zhufu 2013-05-25
		*
		* @param mixed $uid 可以直接传入用户的ID，也可以传入用户的登录认证码
		*/
		public function user_extend_info($uid){
			if(!is_numeric($uid)){
				$uid = $this->user_is_login($uid);
				if(!$uid){
					return false;
				}
			}
			$sql = "SELECT * FROM {$this->table_user_extend} WHERE uid={$uid}";
			return $this->memcache_findone($sql, false);
		}


		/**
		* 返还坐标原点
		* @author yufu 2013-01-31 10:20:15
		* @param float $lng
		* @param float $lat
		* @param  float $distance  半径
		* @return mixed
		*/
		public function returnSquarePoint($lng,$lat,$distance= 0.5){
			define(EARTH_RADIUS, 6371);//地球半径，平均半径为6371km
			$dlng= 2 * asin(sin($distance/ (2 * EARTH_RADIUS)) /cos(deg2rad($lat)));
			$dlng= rad2deg($dlng);

			$dlat=$distance/EARTH_RADIUS;
			$dlat= rad2deg($dlat);

			return array(
			'left-top'=>array('lat'=>$lat+$dlat,'lng'=>$lng-$dlng),
			'right-top'=>array('lat'=>$lat+$dlat,'lng'=>$lng+$dlng),
			'left-bottom'=>array('lat'=>$lat-$dlat,'lng'=>$lng-$dlng),
			'right-bottom'=>array('lat'=>$lat-$dlat,'lng'=>$lng+$dlng)
			);
		}

		/**
		*求两个已知经纬度之间的距离,单位为米  //根据经纬度计算距离
		* @author yufu 2013-02-19 14:14:37
		*@param lng1,lng2 经度
		*@param lat1,lat2 纬度
		*@return float 距离，单位米
		*/
		function GetDistance($lng1,$lat1,$lng2,$lat2)
		{
			//将角度转为狐度
			$radLat1=deg2rad($lat1);
			$radLat2=deg2rad($lat2);
			$radLng1=deg2rad($lng1);
			$radLng2=deg2rad($lng2);
			$a=$radLat1-$radLat2;//两纬度之差,纬度<90
			$b=$radLng1-$radLng2;//两经度之差纬度<180
			$s=2*asin(sqrt(pow(sin($a/2),2)+cos($radLat1)*cos($radLat2)*pow(sin($b/2),2)))*6378.137*1000;
			return $s;
		}



		/******************  商家操作  *************************************************/
		/**
		* 检查商家登录
		* @author zhufu 2013-06-05
		*
		* @param string $loginkey 商家的登录认证码
		*/
		public function cmp_is_login($loginkey){
			if(!$loginkey){
				return false;
			}
			$login_ary=$this->loginkey_change($loginkey);
			$cmp_info = $this->cmp_info_uid($login_ary[0]);
			if(!$cmp_info || $cmp_info['account'] != $login_ary[2] || $cmp_info['password'] != $login_ary[3]){
				return false;
			}
			return $cmp_info['uid'];
		}

		/**
		* 根据UID得到商家信息
		* @author zhufu 2013-06-05
		*
		* @param int $uid 商家ID
		*/
		public function cmp_info_uid($uid){
			if(!is_numeric($uid)){
				return false;
			}
			$sql = "SELECT * FROM {$this->table_user_base} WHERE id={$uid} AND company_id>0";
			$base_info = $this->_mysql(0)->findone($sql);
			if(!$base_info){
				return false;
			}
			$sql = "SELECT * FROM {$this->table_company} WHERE uid={$base_info['id']}";
			$row = $this->_mysql(0)->findone($sql);
			$row['account'] = $base_info['account'];
			$row['password'] = $base_info['password'];
			return $row;
		}



		/**
		* 用户摇奖次数修改
		* @author zhufu 2013-06-09
		*
		* @param int $uid 用户ID
		* @param int $count 大于0为增加，小于0为减少
		*/
		public function user_rock_num_change($uid, $count){
			if(!is_numeric($count)){
				return false;
			}

			$sql = "UPDATE {$this->table_user_extend} SET rock_num_last={$count},rock_num_time=".time()." WHERE uid={$uid}";
			return $this->_mysql(0)->query($sql, true);
		}


		/**
		* 用户商家摇奖摇奖次数修改
		* @author zhufu 2013-06-09
		*
		* @param int $uid 用户ID
		* @param int $count 大于0为增加，小于0为减少
		*/
		public function user_rock_num_cmp_change($uid, $count){
			if(!is_numeric($count)){
				return false;
			}

			$sql = "UPDATE {$this->table_user_extend} SET rock_num_ever_last={$count},rock_num_ever_time=".time()." WHERE uid={$uid}";
			return $this->_mysql(0)->query($sql, true);
		}



		/**
		* 得到图片的绝对地址
		* @author zhufu 2013-06-15
		*
		*/
		public function img_absolute_url($orig_url){
			global $_site;
			if(!$orig_url){
				return '';
			}
			if(strpos($orig_url, 'http') === false){
				//没有http开头
				return $_site->site_config['img']['url'] . $orig_url;
			}
			return $orig_url;
		}

		/**
		* 修改小区的用户数量
		* @author zhufu 2013-07-01
		*
		* @param int $num 小区人数的变化量
		* @param int $cid 小区ID
		*/
		public function community_user_count($cid, $num){
			if(!is_numeric($num) || !is_numeric($cid)){
				return false;
			}
			$tmp = $num > 0 ? '+' . $num : '-' . abs($num);
			$sql = "UPDATE {$this->table_community} SET user_count=user_count{$tmp} WHERE id={$cid}";
			return $this->_mysql(0)->query($sql, true);
		}

		/**
		* 短信发送接口
		* @author zhufu 2013-07-29
		*
		* @param mobile $phone 手机号
		* @param string $msg 消息内容
		*/
		protected function sms_send($phone, $msg){
			if(!is_mobile($phone) || !$msg){
				return false;
			}
			return $this->_sms()->sms_send($phone, $msg);
		}


		/**
		* 获得个人用户基础信息
		* @author limin  2013-8-16  AM 10:04:00
		* @param  string  $param  账号参数
		*/
		public function _out_info_base($param){
			if(!$param){
				return false;
			}
			//选择where 条件
			if(is_numeric($param) && !is_mobile($param)){
				$where = 'id='.$param;
			}else if(is_numeric($param) && is_mobile($param)){
					$where=" mobile={$param} ";
				}
				else{
					$where = "account='{$param}'";
			}

			//查询表
			$table=$this->table_user;

			//查询数据库
			$sql = "SELECT * FROM {$table} WHERE {$where}";
			return $this->memcache_findone($sql);
		}
		/**
		* 检查物管用户信息
		* @author xiezhihui 14-03-11 02:06
		* @param mixed $account
		* @return mysql对象
		*/
		public function _out_info_base_wg($account){
			if(!$account){
				return false;
			}
			$sql = "SELECT a.*,b.cid,b.title as name,b.phone,b.city,b.city_name FROM {$this->table_user_base} as a left join {$this->table_section}  as  b on a.id=b.uid WHERE a.account='{$account}' ";
			return $this->memcache_findone($sql);
		}


		/**
		* 得到开通小区的价格配置
		* @author zhufu 2013-09-11
		*
		* @param int $city 城市ID
		* @param int $year 开通的年限
		*/
		public function out_xiaoqu_price_config($city, $year=0){
			$info = $this->out_xiaoqu_price_info($city);
			if($info){
				return $this->_parse_config($info['config']);
			}
			$tmp1 = substr($city, 0, 4) . 00;
			if($tmp1 != $city){
				$info = $this->out_xiaoqu_price_info($city);
				if($info){
					return $this->_parse_config($info['config']);
				}
			}
			$tmp2 = substr($city, 0, 2) . 0000;
			if($tmp1 != $city){
				$info = $this->out_xiaoqu_price_info($city);
				if($info){
					return $this->_parse_config($info['config']);
				}
			}
			$info = $this->out_xiaoqu_price_info(0);
			return $this->_parse_config($info['config']);
		}
		/**
		* 根据城市得到配置信息
		* @author zhufu 2013-09-18
		*
		* @param int $city 城市ID
		*/
		private function out_xiaoqu_price_info($city){
			$sql = "SELECT * FROM {$this->table_admin_proxy_config} WHERE `area`={$city}";
			return $this->memcache_findone($sql);
		}

	/**
	* 将配置解析为数组
	* @author zhufu 2013-09-18
	*
	* @param string $config 配置
	*/
	private function _parse_config($config){
		if(!$config){
			return false;
		}
		$tmp = explode(';', $config);
		if(!$tmp){
			return false;
		}
		$result = array();
		foreach($tmp as $k=>$v){
			$tmp2 = explode('/', $v);
			$tmp2[0] = explode(',', '0,'.$tmp2[0]);
			unset($tmp2[0][0]);
			$result[$tmp2[1]] = $tmp2[0];
		}
		return $result;
	}
    
    /**
        * 添加软件崩溃日志
        * @author leiqianyong 2014-05-05
        * 
        * @param mixed $data
        */
        public function api_crash_logs($data){
            $data['time'] = time();

            $this->set_db($this->table_crash_log,$data);
        }

    
		/******************  私有方法  *************************************************/


	}
?>